<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchSeatPage, getSeatById, createSeat, updateSeat, deleteSeat, batchDeleteSeat } from '@/api/seat.js'
import { fetchCinemaPage } from '@/api/cinema.js'

// 列表与分页状态
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

const query = reactive({
  pageNo: 1,
  pageSize: 10,
  cinemaId: undefined,
  hallName: '',
  seatNo: '',
  seatType: '', // NORMAL / VIP
})

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增座位')

const form = reactive({
  id: undefined,
  cinemaId: undefined,
  hallName: '',
  seatNo: '',
  seatType: '',
})

const rules = {
  cinemaId: [{ required: true, message: '请选择影院或填写影院ID', trigger: 'blur' }],
  hallName: [{ required: true, message: '请输入影厅名称', trigger: 'blur' }],
  seatNo: [{ required: true, message: '请输入座位号', trigger: 'blur' }],
  seatType: [{ required: true, message: '请选择座位类型', trigger: 'change' }],
}

// 影院列表用于选择（可选）
const cinemaOptions = ref([])

// @function loadCinemaOptions
// @description 加载影院下拉选项，便于在表单中选择影院
// @returns {Promise<void>}
async function loadCinemaOptions() {
  try {
    const res = await fetchCinemaPage({ pageNo: 1, pageSize: 100 })
    const list = res?.data?.records || []
    cinemaOptions.value = list.map((c) => ({ label: c.cname, value: c.id }))
  } catch (e) {
    cinemaOptions.value = []
  }
}

// @function loadData
// @description 加载座位分页数据
// @returns {Promise<void>}
async function loadData() {
  loading.value = true
  try {
    const res = await fetchSeatPage({
      pageNo: query.pageNo,
      pageSize: query.pageSize,
      cinemaId: query.cinemaId,
      hallName: query.hallName || undefined,
      seatNo: query.seatNo || undefined,
      seatType: query.seatType || undefined,
    })
    tableData.value = res?.data?.records || []
    total.value = Number(res?.data?.total || 0)
  } finally {
    loading.value = false
  }
}

// @function handleQuery
// @description 执行查询并重置到第一页
function handleQuery() {
  query.pageNo = 1
  loadData()
}

// @function resetQuery
// @description 重置查询条件并刷新
function resetQuery() {
  query.cinemaId = undefined
  query.hallName = ''
  query.seatNo = ''
  query.seatType = ''
  query.pageNo = 1
  loadData()
}

// @function handleAdd
// @description 打开新增座位对话框
function handleAdd() {
  dialogTitle.value = '新增座位'
  Object.assign(form, { id: undefined, cinemaId: undefined, hallName: '', seatNo: '', seatType: '' })
  dialogVisible.value = true
}

// @function handleEdit
// @description 打开编辑座位对话框，并尝试拉取最新详情
// @param {Object} row - 当前行数据
async function handleEdit(row) {
  dialogTitle.value = '编辑座位'
  Object.assign(form, row)
  dialogVisible.value = true
  try {
    const res = await getSeatById(row.id)
    const detail = res?.data
    if (detail && typeof detail === 'object') {
      Object.assign(form, detail)
    }
  } catch (e) {
    // 拉取失败忽略，使用表格中的数据
  }
}

// 引用 formRef 用于校验
const formRef = ref()

// @function submitForm
// @description 提交新增或更新表单
async function submitForm() {
  try {
    await formRef.value?.validate()
  } catch (e) {
    return
  }
  // 规范化输入，避免大小写或空白导致重复
  form.hallName = (form.hallName || '').trim()
  form.seatNo = ((form.seatNo || '').trim()).toUpperCase()
  form.seatType = (form.seatType || '').trim()
  const payload = {
    id: form.id,
    cinemaId: form.cinemaId,
    hallName: form.hallName,
    seatNo: form.seatNo,
    seatType: form.seatType,
  }
  try {
    let res
    if (payload.id) {
      res = await updateSeat(payload)
    } else {
      res = await createSeat(payload)
    }
    if (String(res?.code) === '200') {
      ElMessage.success(res?.msg || '操作成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(res?.msg || '操作失败')
    }
  } catch (e) {
    ElMessage.error('请求失败，请稍后重试')
  }
}

// @function handleDelete
// @description 删除单条座位数据
// @param {Object} row - 当前行数据
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确定删除座位：${row.hallName} - ${row.seatNo}？`, '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await deleteSeat(row.id)
    if (String(res?.code) === '200') {
      ElMessage.success(res?.msg || '删除成功')
      loadData()
    } else {
      ElMessage.error(res?.msg || '删除失败')
    }
  } catch (e) {
    ElMessage.error('请求失败，请稍后重试')
  }
}

// 多选
const multipleSelection = ref([])

// @function handleSelectionChange
// @description 表格多选变化
// @param {Array<Object>} val - 选择的行数组
function handleSelectionChange(val) {
  multipleSelection.value = val
}

// @function handleBatchDelete
// @description 批量删除选中的座位
async function handleBatchDelete() {
  const ids = (multipleSelection.value || []).map((x) => x.id)
  if (!ids.length) {
    ElMessage.info('请先选择要删除的座位')
    return
  }
  try {
    await ElMessageBox.confirm(`确定批量删除选中的 ${ids.length} 项？`, '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await batchDeleteSeat(ids)
    if (String(res?.code) === '200') {
      ElMessage.success(res?.msg || '批量删除成功')
      loadData()
    } else {
      ElMessage.error(res?.msg || '批量删除失败')
    }
  } catch (e) {
    ElMessage.error('请求失败，请稍后重试')
  }
}

// 分页
// @function handleSizeChange
// @description 切换分页大小
// @param {number} size - 每页大小
function handleSizeChange(size) {
  query.pageSize = size
  query.pageNo = 1
  loadData()
}

// @function handleCurrentChange
// @description 切换当前页码
// @param {number} page - 页码
function handleCurrentChange(page) {
  query.pageNo = page
  loadData()
}

onMounted(() => {
  loadCinemaOptions()
  loadData()
})
</script>

<template>
  <div class="page-container">
    <!-- 查询区域 -->
    <el-card class="query-card" shadow="never">
      <el-form :inline="true" :model="query">
        <el-form-item label="影院">
          <el-select v-model="query.cinemaId" placeholder="选择影院" clearable filterable style="width:220px">
            <el-option v-for="opt in cinemaOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="影厅">
          <el-input v-model="query.hallName" placeholder="请输入影厅名称" clearable style="width:220px" />
        </el-form-item>
        <el-form-item label="座位号">
          <el-input v-model="query.seatNo" placeholder="如 A10" clearable style="width:160px" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="query.seatType" placeholder="全部" clearable style="width:160px">
            <el-option label="普通" value="NORMAL" />
            <el-option label="VIP" value="VIP" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="toolbar">
      <div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>
    </div>

    <!-- 列表 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="cinemaName" label="影院" min-width="160" />
        <el-table-column prop="hallName" label="影厅" min-width="120" />
        <el-table-column prop="seatNo" label="座位号" min-width="100" />
        <el-table-column prop="seatType" label="类型" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.seatType === 'VIP'" type="warning">VIP</el-tag>
            <el-tag v-else type="info">普通</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="160" />
        <el-table-column prop="updatedAt" label="更新时间" min-width="160" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          :current-page="query.pageNo"
          :page-size="query.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="影院" prop="cinemaId">
          <el-select v-model="form.cinemaId" placeholder="选择影院" filterable clearable style="width:320px">
            <el-option v-for="opt in cinemaOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="影厅" prop="hallName">
          <el-input v-model="form.hallName" placeholder="请输入影厅名称" clearable />
        </el-form-item>
        <el-form-item label="座位号" prop="seatNo">
          <el-input v-model="form.seatNo" placeholder="如 A10" clearable />
        </el-form-item>
        <el-form-item label="类型" prop="seatType">
          <el-select v-model="form.seatType" placeholder="请选择类型" clearable>
            <el-option label="普通" value="NORMAL" />
            <el-option label="VIP" value="VIP" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.query-card {
  padding-bottom: 8px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-card {
  padding-bottom: 8px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>